#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <stdlib.h>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //readBtData();

    readThenWriteAnnonBtData();
}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::readBtData()
{
    QString pathToData =  "../../../Data/Contigs/Contigs-updated/Cry3_contigs.gff2";
    QFile gff2(pathToData);

    if( !gff2.exists() )
    {
        qDebug() << "file not found." << endl;
        return false;
    }

    if( ! gff2.open(QIODevice::ReadOnly))
    {
        qDebug() << "file " << pathToData << " can't be opened." << endl;
        return false;
    }

    qDebug() << "file " << pathToData << " opened." << endl;

    //this is for csv files... works for now
    QTextStream stream(&gff2);
    QHash< QString, int > contigHash;
    QString line;//get each line
    do {
         line = stream.readLine();
         qDebug() << line << endl;
         if( ! line.startsWith("#") )
         {
            QStringList list = line.split("\t", QString::SkipEmptyParts);
            qDebug() << "   1 = " << list[0] << endl;

            //FIND CONTIG to which the gene in this line belongs
            int contigIdx = -1;
            if( !contigHash.contains( list[0] ) )//if not encountered yet
            {
                qDebug() << "contig "<<  list[0] << " not yet encountered " << endl;
                contigs << new Contig( list[0] ); //create contig
                contigHash.insert( list[0], contigs.size()-1 );//add to hash table- so can find later
                contigIdx = contigs.size()-1;
            }
            else
            {
                contigIdx = contigHash.value( list[0] );
                qDebug() << "already found list[0] = " << list[0] << " idx = " << contigIdx << " in the contig array, id = " << contigs[contigIdx]->contigId << endl;
            }

            //ADD mRNA from this line to contig
            if( list[2].contains( "mRNA") )
            {
                int start = list[3].toInt();//gene start
                int stop = list[4].toInt(); //gene stop
                //nothing in  5
                QString strand = list[6];//+ or -
                bool pos = true; //positive strand or negative strand
                if( strand.contains( "-") )
                    pos = false;
                //isolate gene key to get into annotation files
                QStringList annot = list[8].split( ";", QString::SkipEmptyParts);
                qDebug() << "isolating gene key = " << annot[0];
                QString geneKey = annot[0].remove("ID=");//.remove(".cdna");
                qDebug() << "geneKey = " << geneKey << endl;

                contigs[contigIdx]->addGene(geneKey, start, stop, pos);
            }

         }
    } while (!stream.atEnd() );

    return true;
}

bool MainWindow::readThenWriteAnnonBtData()
{
    //srand( time(NULL) );

//    int letter1 = 65;  //not using right now
//    int letter2 = 78;
//    int letter2 = 97;
//    int letter3 = 106;

    QString pathToData =  "../../../Data/Contigs/Contigs-updated/Cry3_contigs.gff2";
    QFile gff2(pathToData);
    QFile out("annonData.txt");

    if( !gff2.exists() )
    {
        qDebug() << "file not found." << endl;
        return false;
    }

    if( ! gff2.open(QIODevice::ReadOnly))
    {
        qDebug() << "file " << pathToData << " can't be opened." << endl;
        return false;
    }

    if( ! out.open( QIODevice::WriteOnly ) )
    {
        qDebug() << "failed to open output file " << endl;
        return false;
    }

    qDebug() << "file " << pathToData << " opened." << endl;

    int geneCount = 0;

    //this is for csv files... works for now
    QTextStream stream(&gff2);
    QTextStream annonOut(&out);
    QHash< QString, int > contigHash;
    QHash < QString, int > geneHash;
    QString line;//get each line
    do {
         line = stream.readLine();
         qDebug() << line << endl;
         QString annonContig = "contig";
         if( ! line.startsWith("#") )
         {
            QStringList list = line.split("\t", QString::SkipEmptyParts);
            qDebug() << "   1 = " << list[0] << endl;

            //FIND CONTIG to which the gene in this line belongs
            int contigIdx = -1;
            if( !contigHash.contains( list[0] ) )//if not encountered yet
            {
                contigs << new Contig( list[0] ); //create contig
                contigHash.insert( list[0], contigs.size()-1 );//add to hash table- so can find later
                contigIdx = contigs.size()-1;

                annonContig = annonContig.append(QString("%1").arg( contigIdx ) );
                qDebug() << "making annon gene name for "<< list[0]  << " it is  " << annonContig << endl;
            }
            else
            {
                contigIdx = contigHash.value( list[0] );
                annonContig = annonContig.append( QString("%1").arg(contigIdx) );
                qDebug() << "already found annon  name for "<< list[0]  << " it is  " << annonContig << endl;

                //qDebug() << "already found list[0] = " << list[0] << " idx = " << contigIdx << " in the contig array, id = " << contigs[contigIdx]->contigId << endl;
            }

            //ADD mRNA from this line to contig
            if( list[2].contains( "mRNA") )
            {
                //get gene key
                QStringList annot = list[8].split( ";", QString::SkipEmptyParts);
                QString geneKey = annot[0].remove("ID=");

                QString geneLookup = geneKey;

                qDebug() << annot.size() << endl;

                if( list[8].contains("Note") )
                {
                    if( annot[2].contains("Note=") )
                    {
                        qDebug() << " ID = " << annot[2] << endl;
                        QStringList parseAnnot = annot[2].split(":");
                        QString uniprot = parseAnnot[0].remove("Note=");
                        qDebug() << uniprot << endl;
                        geneLookup = uniprot;
                    }
                    else
                        qDebug() << " This annotation does not have a name" << endl;
                }


                //see if it has been found
                QString annonName = "gene";//i will add to this string to give it an annon name
                if( !geneHash.contains( geneLookup ) )//if not encountered yet
                {
                    geneCount++; //why incr first= because want it to start at 1
                    annonName = annonName.append( QString("%1").arg(geneCount));
                    geneHash.insert( geneLookup, geneCount );//add to hash table- so can find later
                    qDebug() << "making annon gene name for "<< geneLookup  << " it is  " << annonName << endl;
                }
                else
                {
                    int geneIdx = geneHash.value( geneLookup );
                    annonName.append( QString("%1").arg(geneIdx) );
                    qDebug() << "already found annon name for " << geneKey << ", it is " << annonName << " in the contig array, id = " << contigs[contigIdx]->contigId << endl;
                }

                int start = list[3].toInt();//gene start
                int stop = list[4].toInt(); //gene stop
                //nothing in  5
                QString strand = list[6];//+ or -
                bool pos = true; //positive strand or negative strand
                if( strand.contains( "-") )
                    pos = false;

                //contigs[contigIdx]->addGene(geneKey, start, stop, pos);

                annonOut << annonContig << "\t" << annonName << "\t" << start <<  "\t" << stop << "\t" << strand << "\n";
            }

         }
    } while (!stream.atEnd() );

    return true;
}
